package org.example.physics_engine.collision.manifold;


import org.example.physics_engine.geometry.Vector2d;
import org.example.physics_engine.geometry.shapes.AbstractShape;
import org.example.physics_engine.geometry.shapes.QuarterCircle;


//接触流形（接触曲面）求解器，将Penetration解析为Manifold
public class ManifoldSolver {

    //基于Penetration计算出碰撞流形
    /*
    * 参数
    * penetration 穿透信息
    * shape1 被碰撞图形
    * shape2 碰撞图形
    * shape 近似图形
    * manifold 碰撞点信息
     */
    public boolean getManifold(Penetration penetration, AbstractShape shape1, AbstractShape shape2, AbstractShape shape, Manifold manifold) {
        if (shape != null) {
            if (shape1 instanceof QuarterCircle) {
                shape1 = shape;
            } else if (shape2 instanceof QuarterCircle) {
                shape2 = shape;
            }
        }
        // 获得分离法线的单位向量（理论上已被规范化）
        Vector2d n = penetration.getPenetrationNormal();
        Vector2d vertex = shape1.getFarthestFeature(n);

        if (vertex != null) {
            ManifoldPoint mp = new ManifoldPoint(vertex, penetration.getDepth());
            manifold.getPoints().add(mp);
            manifold.getNormal().x = -n.x;
            manifold.getNormal().y = -n.y;
            return true;
        }

        Vector2d ne = n.getNegative();
        Vector2d vertex2 = shape2.getFarthestFeature(ne);
        if (vertex2 != null) {
            ManifoldPoint mp = new ManifoldPoint(vertex2, penetration.getDepth());
            manifold.getPoints().add(mp);
            manifold.getNormal().x = ne.x;
            manifold.getNormal().y = ne.y;
            return true;
        }
        // 不考虑多边形之间的碰撞
        return false;
    }

}
